package com.lg.head_first.chap02.observer.simple;

import java.util.ArrayList;
import java.util.List;

/**
 * @author by Mr. Li 2020/7/31 15:25
 */
public class SimpleSubject implements Subject {
    /**
     * 用于存放所有的注册 Observer
     */
    private List<Observer> observers;

    private int value = 0;

    public SimpleSubject() {
        this.observers = new ArrayList<>();
    }

    public void registerObserver(Observer observer) {
        observers.add(observer);
    }

    @Override
    public void removeObserver(Object observer) {
        int i = observers.indexOf(observer);
        if (i >= 0)
            observers.remove(i);
    }

    @Override
    public void notifyObserver() {
        if (observers.size() > 0) {
            for (Observer observer : observers) {
                observer.update(value);
            }
        }
    }

    public void setValue(int value) {
        this.value = value;
        notifyObserver();
    }
}
